from core.spider.easy.EasyTaskBuidder import *
from core.spider.easy.EasyTaskContext import *
from core.tasks.TasksQueue import *
from core.spider.SpiderTaskEngine import *


class SpiderFactory:

    # 创建一个线程锁
    lock = threading.Lock()

    tasksQueue = None

    def __init__(self):
        self.tasksQueue = TasksQueue()


    #开始执行
    def execute(self):
        self.tasksQueue.execute()

    #启动任务
    def start(self,task):
        with self.lock:
            isExists  = self.tasksQueue.is_exists(task.id)
            if isExists: return False
            print('开始启动')
            spiderTaskEngine = SpiderTaskEngine(task)

            self.tasksQueue.put(spiderTaskEngine)

            return True

    #停止任务
    def stop(self,task):
        with self.lock:
            spiderTaskEngine  = self.tasksQueue.get(task.id)
            if spiderTaskEngine is None: return False

            return spiderTaskEngine.stop()

    #暂停
    def paused(self):
        self.tasksQueue.paused()

    #队列任务数量(包括队列中，运行中)
    def get_task_count(self):
        return self.tasksQueue.get_task_count()
